from PyQt4 import QtGui, QtCore
from usbdebug_uiHandler import usbdebug_uiHandler
from time import sleep
from time import ctime
from ctypes import *
import math
import threading
import os
import thread
import types
import Util

data= ( c_char * 512) ()
dll = cdll.LoadLibrary('cydesc.dll')

class MainWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self)
        
        self.ui = usbdebug_uiHandler()
        self.flags = {"__isopen__": False, "__datatype__": "ascii","__updata__": False}
        
        self.ui.setupUi(self)
        self.ui.setupWidget(self)
        self.__setupSignal()
    
    def closeEvent(self, e):
        if self.flags["__isopen__"]:
            self.serial.terminate()
        e.accept()
        
    def __setupSignal(self):
        self.ui.reButton.clicked.connect(self.__onRecoverPort)
        self.ui.sendButton.clicked.connect(self.__onSendData)
        self.ui.clearHistoryButton.clicked.connect(self.ui.clearHistory)
        self.ui.clearLcdButton.clicked.connect(self.ui.clearLcdNumber)
    def __onRecoverPort(self, settings=None):
        num=dll.finddevice()
        if num>=1:
            dll.recverdata(0x86,data,512)
            data2 = Util.toVisualHex(data)
            self.ui.chatTextBrowser.append('<b>Recv</b> @%s<br/><font color="yellow">%s</font><br/><br/>'% (ctime(), data2))
        else:
            self.ui.chatTextBrowser.append('no connect USBdebuger please connect')

    def __onSendData(self, data=None, _type="hex"):
            data= self.ui.sendTextEdit.toPlainText()
            print data
            cdata= ( c_char * 512) ()
            cdata=None
            tmpdata=str(data)
            tmpdata = ''.join(tmpdata.split())
            tmpdata = ' '.join([tmpdata[i:i+2] for i in xrange(0, len(tmpdata), 2)]).upper()
            tmpdata = Util.toHex(''.join(tmpdata.split()))
            cdata=tmpdata
            num=dll.finddevice()
            if num>=1:
                dll.senddata(0x02,cdata,512)
                data2 = Util.toVisualHex(cdata)
                self.ui.chatTextBrowser.append('<b>Recv</b> @%s<br/><font color="yellow">%s</font><br/><br/>'% (ctime(), data2))
            else:
                self.ui.chatTextBrowser.append('no connect USBdebuger please connect')